package com.naizhuai.ui.user.register;


import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.naizhuai.MainActivity;
import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.R;
import com.naizhuai.network.NetWorkObserver;
import com.naizhuai.network.apistore.UserManageDataApiStore;
import com.naizhuai.ui.BaseFragment;
import com.naizhuai.ui.components.ClearWriteEditText;
import com.naizhuai.ui.components.CustomTextWatch;
import com.naizhuai.ui.user.UserLogin;
import com.naizhuai.ui.user.UserManageDataApiStoreIml;
import com.naizhuai.util.ConstantsPersonResources;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class RegisterFragment extends BaseFragment {
    public static final String PHONENUMBER = "phonenumber";
    public static final int COUNTDOWM_FACTOR = 5;
    @BindView(R.id.headToolBar)
    Toolbar headToolBar;
    @BindView(R.id.markword)
    TextView markword;
    @BindView(R.id.hintNumber)
    TextView hintNumber;
    @BindView(R.id.ed_username)
    ClearWriteEditText edUsername;
    @BindView(R.id.ed_identifying_code)
    ClearWriteEditText edIdentifyingCode;
    @BindView(R.id.tv_countdown)
    TextView tvCountdown;
    @BindView(R.id.ed_password)
    ClearWriteEditText edPassword;
    @BindView(R.id.btn_register)
    Button btnRegister;
    @BindView(R.id.detail_content_card)
    CoordinatorLayout detailContentCard;
    private Unbinder unbinder;
    private  CountDownTimer timer;
    public RegisterFragment() {

    }

    public static RegisterFragment newInstance(@NonNull String phoneNumber) {
        RegisterFragment fragment = new RegisterFragment();
        Bundle args = new Bundle();
        args.putString(PHONENUMBER, phoneNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_register, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        InitToolBar();
        InitNumberHint();
        InitCountDown();
        InitEd();
        InitBtn();
    }

    private void InitBtn() {
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 String nickName=edUsername.getText().toString().trim();
                 String code=edIdentifyingCode.getText().toString().trim();
                 String password=edPassword.getText().toString().trim();
                 if (TextUtils.isEmpty(nickName)){
                     shortToast(getString(R.string.please_nick_name));
                     return;
                 }
                if (TextUtils.isEmpty(code)){
                    shortToast(getString(R.string.please_identifying_code));
                    return;
                }
                if (TextUtils.isEmpty(password)){
                    shortToast(getString(R.string.please_password));
                    return;
                }

//                UserManageDataApiStore userManageDataApiStore = UserManageDataApiStoreIml.getInstance();
//                userManageDataApiStore.userRegister(nickName,getArguments().getString(PHONENUMBER),
//                                                    code, password)
//                        .subscribe(new NetWorkObserver<UserLogin>() {
//                            @Override
//                            protected void onFail(String errormsg) {
//                                shortToast(errormsg);
//                            }
//                            @Override
//                            protected void onSuccess(UserLogin userLogin) {
//                                //更新一下sp里面的数据
//                                saveUidSid(userLogin.getUid(),userLogin.getSid());
//                                Intent intent=new Intent(getActivity(), MainActivity.class);
//                                startActivity(intent);
//                                shortToast(getString(R.string.login_ok));
//                                getActivity().finish();
//                            }
//                        });
            }
        });
    }

    private void saveUidSid(String uid,String sid) {
        getSp().saveValue(PersonUserBean.USER_ID_KEY, uid);
        getSp().saveValue(ConstantsPersonResources.SESSION_ID_KEY, sid);
    }

    private void InitCountDown() {
        tvCountdown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendSms();
            }
        });
        startCountDown();
    }

    private void startCountDown() {
        tvCountdown.setEnabled(false);
         timer = new CountDownTimer(COUNTDOWM_FACTOR * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                tvCountdown.setText(getString(R.string.count_down_again_send,millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                tvCountdown.setEnabled(true);
                tvCountdown.setText(getString(R.string.again_send));
            }
        }.start();
    }

    private void sendSms() {
        startCountDown();
    }

    private void InitNumberHint() {
        String phonenumber = getArguments().getString(PHONENUMBER);
        String tempString = getString(R.string.sendsms_alreaday);
        SpannableString spannableString = new SpannableString(tempString + phonenumber);
        spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.blue_pressed)), tempString.length(), spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        hintNumber.setText(spannableString);
    }


    private void InitEd() {
        setTextWatch(edUsername);
        setTextWatch(edIdentifyingCode);
        setTextWatch(edPassword);
    }


    private void setTextWatch(EditText editText) {
        editText.addTextChangedListener(new CustomTextWatch() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                changeBtnState();
            }
        });
    }

    private void changeBtnState() {
        String realName = edUsername.getText().toString().trim();
        String code = edIdentifyingCode.getText().toString().trim();
        String password = edPassword.getText().toString().trim();
        if (!TextUtils.isEmpty(realName)
                && !TextUtils.isEmpty(code)
                && !TextUtils.isEmpty(password)) {
            btnRegister.setEnabled(true);
        } else {
            btnRegister.setEnabled(false);
        }
    }

    private void InitToolBar() {
        headToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getFragmentManager().popBackStack();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        if (timer!=null){
            timer.cancel();
        }
    }

}
